<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <canvas id="c" width="400" height="400" style="border: 1px solid #ccc"></canvas>

        <script>
            const context = document.getElementById('c')
            const ctx = context.getContext('2d')
            const img = new Image() // 创建图片对象
            img.src = './image/flower.png' // 加载本地图片

            // 图片加载完成后在执行其他操作
            img.onload = () => {
                // 渲染图片
                ctx.drawImage(img, 0, 0)
                // 获取图片信息

                const imageData = ctx.getImageData(0, 0, img.width, img.height)
                console.log('imageData: ', imageData)
                for (let i = 0; i < imageData.data.length; i += 4) {
                    // 添加上透明度
                    // imageData.data[i + 3] = imageData.data[i + 3] * 0.5

                    // 变成黑白的图片
                    let avg = (imageData.data[i]+imageData.data[i+1]+imageData.data[i+2])/3
                    imageData.data[i] = avg;
                    imageData.data[i+1] = avg;
                    imageData.data[i+2] = avg;
                }
                ctx.putImageData(imageData, 0, 0,200,200,200,200)
            }
        </script>
    </body>
</html>
